package com.ruoyi.quartz.task;

import cn.hutool.log.Log;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.TOrderInfo;
import com.ruoyi.business.domain.TRecipientInfo;
import com.ruoyi.business.param.MsgPayResult;
import com.ruoyi.business.service.ChargeService;
import com.ruoyi.business.service.ITOrderInfoService;
import com.ruoyi.business.service.ITRecipientInfoService;
import com.ruoyi.business.service.LoginService;
import com.ruoyi.common.utils.HttpResponse;
import com.ruoyi.common.utils.HttpUtils;
import com.ruoyi.common.utils.MoneyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Component
public class AlikmtOrderCheckTask {


    @Resource
    private ITOrderInfoService orderService;
    @Resource
    private ITRecipientInfoService userRecipientService;
    @Resource
    private ChargeService chargeService;
    @Resource
    private LoginService loginService;

    private Log logger = Log.get();

    /**
     * 检查支付超时的订单。状态为待支付并且当前时间已经超过有效时间
     */
    @Scheduled(fixedRate = 5000)
    public void checkOrder() throws Exception {
//        logger.info("SYB订单查询..");
        Calendar c = Calendar.getInstance();
        TOrderInfo orderquery = new TOrderInfo();
        orderquery.setChannelType("alipay");
        orderquery.setChannel("alipay_kmt_h5");
        orderquery.setStatus(1);
        List<TOrderInfo> orderInfos = orderService.selectTOrderInfoList(orderquery);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//要转换的时间格式
        String dateTime = sdf.format(new Date());
        HashMap<String, String> headerMap = new HashMap();
        HashMap<String, String> dataMap = new HashMap();
        for (TOrderInfo orderInfo : orderInfos) {
            if (StringUtils.isBlank(orderInfo.getPay3rdOrderNo())) {
                continue;
            }
            TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
            String cookieStr = userRecipientInfo.getCookie();
            JSONObject cookieObj = JSONObject.parseObject(cookieStr);
            String token = cookieObj.getString("token");
            String url = "https://mch.f.52pay.com/api/trade_order/list";
//            logger.info("CEZ订单查询请求：" + url);
            headerMap.put("User-Agent","Mozilla/5.0 (iPhone; CPU iPhone OS 17_1_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.44(0x18002c2f) NetType/WIFI Language/zh_CN");
            headerMap.put("Authorization",token);
            dataMap.put("page","1");
            dataMap.put("limit","50");
            dataMap.put("queryStartDate",dateTime);
            dataMap.put("queryEndDate","");
            dataMap.put("status","2");
            dataMap.put("tradeType","-99");
            dataMap.put("storeId",cookieObj.getString("storeId"));
            HttpResponse httpResponse = HttpUtils.httpFormPost(url,headerMap,"",dataMap,"SYB下单","");
            JSONObject resultObj = JSONObject.parseObject(httpResponse.getBody());
//            logger.info("KMT订单查询.." + resultObj);
            String resultCode = resultObj.getString("code");
            if (resultCode.equals("0")) {
                JSONArray recordObj = resultObj.getJSONArray("data");
                if (recordObj !=null && recordObj.size()>0) {
                    for (int i = 0; i < recordObj.size(); i++) {
                        JSONObject dataObj = (JSONObject) recordObj.get(i);
                        if(dataObj.getString("tradeOrderId").equals(orderInfo.getPay3rdOrderNo())){
                            logger.info("KMT订单查询.." + recordObj.get(i));
                            MsgPayResult msgPayResult = new MsgPayResult();
                            msgPayResult.setChannel(orderInfo.getChannel());
                            msgPayResult.setTradeNo(orderInfo.getId().toString());
                            msgPayResult.setChannelAccount(userRecipientInfo.getChannelAccount());
                            msgPayResult.setOrderId(dataObj.getString("tradeOrderId"));
                            msgPayResult.setRealMoney(MoneyUtil.fenToYuan(orderInfo.getMoney() + ""));
                            msgPayResult.setUid(userRecipientInfo.getUserId().toString());
//                    msgPayResult.setBillTime(timeStamp2Date(recordObj.getString("updateTime")));

                            msgPayResult.setChannelPayMsgResult(JSONObject.toJSONString(recordObj));
                            chargeService.updateOrderPayResult(false, orderInfo.getId(), msgPayResult, false);
                            chargeService.notifyUserPaySucc(orderInfo.getId());

                            logger.info("快米兔订单回调..订单号：" + orderInfo.getId() + " 金额：" + orderInfo.getMoney());
                            break;
                        }
                    }
                }
            }else{
//                loginService.kmtlogin(userRecipientInfo);
            }
        }
    }

    private String timeStamp2Date(String str_num) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//要转换的时间格式
        if (str_num.length() == 13) {
            String date = sdf.format(new Date(Long.parseLong(str_num)));
            return date;
        } else {
            String date = sdf.format(new Date(Integer.parseInt(str_num) * 1000L));
            return date;
        }
    }


}
